/////////////////////////////////////////////////////////////////////////////
// Name:        blurtapp.cpp
// Purpose:     
// Author:      Julian Smart
// Modified by: 
// Created:     18/02/2009 19:13:38
// RCS-ID:      
// Copyright:   
// Licence:     New BSD License
/////////////////////////////////////////////////////////////////////////////

#include "wx/wx.h"

#include "wx/config.h"
#include "wx/stdpaths.h"

#include "blurtapp.h"

////@begin XPM images
////@end XPM images

#include "tts/tts_espeak.h"
#include "tts/tts_cepstral.h"

#ifdef __WXMSW__
#include "tts/tts_sapi.h"
#endif

#ifdef __WXMAC__
#include "tts/tts_macosx.h"
#endif

/*
 * Application instance implementation
 */

////@begin implement app
IMPLEMENT_APP( BlurtApp )
////@end implement app


/*
 * BlurtApp type definition
 */

IMPLEMENT_CLASS( BlurtApp, wxApp )


/*
 * BlurtApp event table definition
 */

BEGIN_EVENT_TABLE( BlurtApp, wxApp )

////@begin BlurtApp event table entries
////@end BlurtApp event table entries

END_EVENT_TABLE()


/*
 * Constructor for BlurtApp
 */

BlurtApp::BlurtApp()
{
    Init();
}


/*
 * Member initialisation
 */

void BlurtApp::Init()
{
////@begin BlurtApp member initialisation
////@end BlurtApp member initialisation
}

/*
 * Initialisation for BlurtApp
 */

bool BlurtApp::OnInit()
{    
////@begin BlurtApp initialisation
	// Remove the comment markers above and below this block
	// to make permanent changes to the code.

#if wxUSE_XPM
	wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
	wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
	wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
	wxImage::AddHandler(new wxGIFHandler);
#endif
	MainFrame* mainWindow = new MainFrame( NULL );
	mainWindow->Show(true);
////@end BlurtApp initialisation

    m_speech.AddHandler(new wxTTSEspeakHandler);
    m_speech.AddHandler(new wxTTSCepstralHandler);
#ifdef __WXMSW__
    m_speech.AddHandler(new wxTTSSapiHandler);
#endif
#ifdef __WXMAC__
    m_speech.AddHandler(new wxTTSMacOSXHandler);
#endif

    m_batchEncoder.GetSpeech().AddHandler(new wxTTSEspeakHandler);
    m_batchEncoder.GetSpeech().AddHandler(new wxTTSCepstralHandler);
#ifdef __WXMSW__
    m_batchEncoder.GetSpeech().AddHandler(new wxTTSSapiHandler);
#endif
#ifdef __WXMAC__
    m_batchEncoder.GetSpeech().AddHandler(new wxTTSMacOSXHandler);
#endif

    // Set a default engine
#ifdef __WXMSW__
    m_speechSettingsInfo.m_engine = wxT("Microsoft SAPI");
#elif defined(__WXMAC__)
    m_speechSettingsInfo.m_engine = wxT("Apple Speech Manager");
#else
    m_speechSettingsInfo.m_engine = wxT("eSpeak");
#endif

    m_speechSettingsInfo.m_speech = & m_speech;

    LoadSettings();
    
    m_speech.SetEngine(m_speechSettingsInfo.m_engine);
    m_batchEncoder.GetSpeech().SetEngine(m_speechSettingsInfo.m_engine);

    InitializeTransformer();

    return true;
}


/*
 * Cleanup for BlurtApp
 */

int BlurtApp::OnExit()
{
    SaveSettings();

////@begin BlurtApp cleanup
	return wxApp::OnExit();
////@end BlurtApp cleanup
}

// Initialize transformer
void BlurtApp::InitializeTransformer()
{
    wxStandardPaths paths;
    wxString dataDir = paths.GetUserDataDir();
    if (!wxDirExists(dataDir))
        wxMkdir(dataDir);

    wxString pronunciationTableFilename = wxTextToSpeech::AppendPaths(dataDir, wxT("pronunciation.txt"));

    if (wxFileExists(pronunciationTableFilename))
    {
        m_transformer.LoadFile(pronunciationTableFilename);
        m_transformer.Index();
    }
    
    m_speech.SetTransformer(& m_transformer);
    m_batchEncoder.GetSpeech().SetTransformer(& m_transformer);
}

// Save pronunciation table
void BlurtApp::SaveTransformer()
{
    wxStandardPaths paths;
    wxString dataDir = paths.GetUserDataDir();
    wxASSERT(!dataDir.IsEmpty());

    if (!wxDirExists(dataDir))
        wxMkdir(dataDir);

    wxString pronunciationTableFilename = wxTextToSpeech::AppendPaths(dataDir, wxT("pronunciation.txt"));
    m_transformer.SaveFile(pronunciationTableFilename);
}

// Delete temporary files
void BlurtApp::DeleteTemporaryFiles()
{
    wxLogNull nullLog;
    size_t i;
    for (i = 0; i < m_tempFilenames.GetCount(); i++)
    {
        if (wxFileExists(m_tempFilenames[i]))
            wxRemoveFile(m_tempFilenames[i]);
    }
}

// Load settings
bool BlurtApp::LoadSettings()
{
    wxConfig config(wxT("Blurt"), _T("Anthemion Software"));

    config.Read(wxT("Speech/Speed"), & m_speechSettingsInfo.m_speed);
    config.Read(wxT("Speech/Volume"), & m_speechSettingsInfo.m_volume);
    config.Read(wxT("Speech/Pitch"), & m_speechSettingsInfo.m_pitch);
    config.Read(wxT("Speech/Engine"), & m_speechSettingsInfo.m_engine);
    config.Read(wxT("Speech/TestText"), & m_speechSettingsInfo.m_testText);

    size_t i;
    for (i = 0; i < (size_t) m_speech.GetHandlerCount(); i++)
    {
        wxTTSHandler* handler = m_speech.GetHandler(i);
        wxString voice, voiceVariant, programLocation, dataLocation;
        config.Read(wxT("Speech/") + handler->GetId() + wxT("Voice"), & voice);
        config.Read(wxT("Speech/") + handler->GetId() + wxT("VoiceVariant"), & voiceVariant);
        config.Read(wxT("Speech/") + handler->GetId() + wxT("ProgramLocation"), & programLocation);
        config.Read(wxT("Speech/") + handler->GetId() + wxT("DataLocation"), & dataLocation);

        if (!voice.IsEmpty())
            handler->SetVoice(voice);
        if (!voiceVariant.IsEmpty())
            handler->SetVoiceVariant(voiceVariant);
        if (!programLocation.IsEmpty())
            handler->SetProgramLocation(programLocation);
        if (!dataLocation.IsEmpty())
            handler->SetDataLocation(dataLocation);
    }

    config.Read(wxT("MP3/UseMP3Encoding"), & m_mp3SettingsInfo.m_enabled);
    config.Read(wxT("MP3/LamePath"), & m_mp3SettingsInfo.m_encoderPath);
    config.Read(wxT("MP3/BitRate"), & m_mp3SettingsInfo.m_bitRate);

    return true;
}

// Save settings
bool BlurtApp::SaveSettings()
{
    wxConfig config(wxT("Blurt"), _T("Anthemion Software"));

    config.Write(wxT("Speech/Speed"), m_speechSettingsInfo.m_speed);
    config.Write(wxT("Speech/Volume"), m_speechSettingsInfo.m_volume);
    config.Write(wxT("Speech/Pitch"), m_speechSettingsInfo.m_pitch);
    config.Write(wxT("Speech/Engine"), m_speechSettingsInfo.m_engine);
    config.Write(wxT("Speech/TestText"), m_speechSettingsInfo.m_testText);

    size_t i;
    for (i = 0; i < (size_t) m_speech.GetHandlerCount(); i++)
    {
        wxTTSHandler* handler = m_speech.GetHandler(i);

        config.Write(wxT("Speech/") + handler->GetId() + wxT("Voice"), handler->GetVoice());
        config.Write(wxT("Speech/") + handler->GetId() + wxT("VoiceVariant"), handler->GetVoiceVariant());
        config.Write(wxT("Speech/") + handler->GetId() + wxT("ProgramLocation"), handler->GetProgramLocation());
        config.Write(wxT("Speech/") + handler->GetId() + wxT("DataLocation"), handler->GetDataLocation());
    }

    config.Write(wxT("MP3/UseMP3Encoding"), m_mp3SettingsInfo.m_enabled);
    config.Write(wxT("MP3/LamePath"), m_mp3SettingsInfo.m_encoderPath);
    config.Write(wxT("MP3/BitRate"), m_mp3SettingsInfo.m_bitRate);

    return true;
}

